package io.knifer.gokexceltask.utils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

@SuppressWarnings("all")
public class AESUtils {

    private static final String AES_ALGORITHM = "AES/ECB/PKCS5Padding";

    // 获取 cipher
    private static Cipher getCipher(byte[] key, int model) throws InvalidKeyException {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = null;

        try {
            cipher = Cipher.getInstance(AES_ALGORITHM);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            // do nothing
        }
        cipher.init(model, secretKeySpec);

        return cipher;
    }

    public static String encryptPlainTextToBase64(String data, byte[] key) throws InvalidKeyException {
        return encryptToBase64(data.getBytes(StandardCharsets.UTF_8), key);
    }

    public static String encryptToBase64(byte[] data, byte[] key) throws InvalidKeyException {
        Cipher cipher = getCipher(key, Cipher.ENCRYPT_MODE);

        return Base64.getEncoder().encodeToString(encrypt(data, key));
    }

    public static byte[] encrypt(byte[] data, byte[] key) throws InvalidKeyException {
        Cipher cipher = getCipher(key, Cipher.ENCRYPT_MODE);
        byte[] result = null;

        try {
            result = cipher.doFinal(data);
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            // do nothing
        }

        return result;
    }

    public static String decryptBase64ToPlainText(String data, byte[] key) throws InvalidKeyException {
        return decryptToPlainText(Base64.getDecoder().decode(data), key);
    }

    public static String decryptToPlainText(byte[] data, byte[] key) throws InvalidKeyException {
        return new String(decrypt(data, key)).intern();
    }

    public static byte[] decryptBase64(String data, byte[] key) throws InvalidKeyException {
        return decrypt(Base64.getDecoder().decode(data), key);
    }

    // AES解密
    public static byte[] decrypt(byte[] data, byte[] key) throws InvalidKeyException {
        Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE);
        byte[] result = null;

        try {
            result = cipher.doFinal(data);
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            // do nothing
            e.printStackTrace();
        }

        return result;
    }
}

